import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wanandroid_flutter/bean/app_response.dart';
import 'package:wanandroid_flutter/bean/project_type_bean.dart';
import 'package:wanandroid_flutter/network/api.dart';

import '../bean/articles_bean.dart';
import '../network/request_util.dart';

class ProjectController extends GetxController with GetSingleTickerProviderStateMixin{
  var tabs = <ProjectTypeBean>[].obs;  //tab导航数据集合

  TabController? tabCtr; //tab导航控制器

  var _pageIndex = 1; //页面索引

  //下拉刷新控制器
  final controller = EasyRefreshController(
      controlFinishRefresh: true, controlFinishLoad: true);

  var projectList=<ArticleBean>[].obs; //项目列表数据集合


  @override
  Future<void> onInit() async {
    super.onInit();
    await httpProjectCategory();
    tabCtr = TabController(length: tabs.length, vsync: this);
    refreshRequest();
    tabCtr?.addListener(() {
      refreshRequest();
    });
  }

  /// 项目列席网络请求
  httpProjectCategory() async {
    AppResponse<List<ProjectTypeBean>> proTypeRes =
        await HttpGo.instance.get(Api.projectCategory);

    if (proTypeRes.isSuccessful) {
      tabs.value = proTypeRes.data ?? [];
    }
  }

  ///下拉刷新
  refreshRequest() async {
    _pageIndex = 1;
    projectList.clear();
    var state = await _httpProjectList();
    controller.finishRefresh(state);
  }

  ///上拉加载
  loadMoreRequest() async {
    _pageIndex++;
    var state = await _httpProjectList();
    controller.finishLoad(state);
  }


  ///项目列表请求
  Future<IndicatorResult> _httpProjectList() async {
    int firstSelect = tabCtr?.index ?? 0;
    int cid = tabs[firstSelect].id;
    AppResponse<ArticleData> articleRes = await HttpGo.instance
        .get("${Api.projectList}$_pageIndex/json/?cid=$cid");
    var list = articleRes.data?.datas ?? [];
    projectList.addAll(list);
    if (articleRes.isSuccessful) {
      if (list.isNotEmpty) {
        return IndicatorResult.success;
      } else {
        return IndicatorResult.noMore;
      }
    } else {
      return IndicatorResult.fail;
    }
  }
}
